﻿
namespace Patterns4Net.PatternEnforcer.Core.Patterns
{
    using System;
    using Patterns4Net.Attributes;

    public abstract class PatternCheckerBase<TPattern> : IPatternChecker where TPattern : class, IPattern
    {
        public CheckerResult Check(IPattern subject)
        {
            var pattern = subject as TPattern;
            if (pattern == null)
            {
                throw new InvalidPatternException(this.GetType().Name, typeof(TPattern).Name, subject.GetType().Name);
            }

            return this.Check(pattern);
        }

        protected abstract CheckerResult Check(TPattern pattern);

        public class InvalidPatternException : ApplicationException
        {
            private const string MessageTemplate =
                @"PatternCheckerBase subclass {0} should check only patterns of type {1} but it 
                got instance of {2} in SetPatternInstance. Have you specified the pattern in 
                PatternCheckerExportAttribute like this [PatternCheckerExport(PatternType={1})?";

            public InvalidPatternException(string className, string expectedPatternName, string actualPatternName)
                : base(string.Format(MessageTemplate, className, expectedPatternName, actualPatternName))
            {                
            }
        }
    }
}
